<template>
  <div class="imgUpload">
    <el-upload
      action="uploadAction"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :before-remove="handleRemove"
      multiple
      :show-file-list="true"
      ref="upload"
      accept=".jpg, .png"
      :headers="headers"
      :on-error="uploadError"
      :on-change="changeFile"
      :file-list="fileList"
      :http-request="httpRequest"
      :before-upload="beforeAvatarUpload"
      :disabled="disabled"
    >
      <i class="el-icon-plus"></i>
      <div slot="tip" class="el-upload__tip">只能上传.jpg, .png文件</div>
    </el-upload>
    <!-- 图片预览 -->
<!--    <el-dialog :visible.sync="imgVisible" title="预览" v-dialog-drag :append-to-body="true">-->
<!--      <div style="width: 100%;text-align: center">-->
<!--        <img style="max-width: 100%" :src="dialogImageUrl" alt="">-->
<!--      </div>-->

<!--    </el-dialog>-->
    <div class="demo-image__preview" v-show="false">
      <el-image
        ref="elImage"
        style="width: 100px; height: 100px"
        :src="dialogImageUrl"
        :preview-src-list="[dialogImageUrl]">
      </el-image>
    </div>
  </div>
</template>

<script>
  import {getToken} from "@/utils/auth"
  import * as imageConversion from 'image-conversion';
  import pdfImg from '@/assets/images/pdf.png'
  export default {
    name: "index",
    data() {
      return {
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        imgVisible: false,
        dialogImageUrl: null,
        fileList: [],
        attachment:[],
      }
    },
    props: ['attachments', 'disabled'],
    created() {
      this.imgVisible = false;
      this.dialogImageUrl = null;
      this.fileList = [];
      this.attachment = this.attachments
      if (this.attachment && this.attachment.length > 0) {
        this.attachment.map((item) => {
          let {fileName: name, fileUrlInner: realurl, fileBase64} = item;
          // 保持fileList
          let url = this.fileListUrl(item);
          let tmpObj = {name, realurl, url,fileBase64};
          this.fileList.push(tmpObj);
        });
      } else {
        this.attachment = []
      }
    },
    methods: {
      handleBeforeName(file) {
        let fileName = file.name.substring(0, file.name.lastIndexOf('.'));
        let isType = true;
        if (!(fileName.length <= 200)) {
          isType = false;
          this.$message.error({
            message: '文件名过长，请修改提交'
          })
        }
        return isType;
      },
      beforeAvatarUpload(file) {
        // // 文件格式判断
        let flag = this.handleBeforeUpload(file);
        if (!flag) {
          return false;
        }
        // 文件名称长度判断
        let flagName = this.handleBeforeName(file);
        if (!flagName) {
          return false;
        }
      },
      //预览图片
      handlePictureCardPreview(file) {
        var fileType = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
        if (fileType == ".png" || fileType == ".webp" || fileType == ".jpg" || fileType == '.jpeg') {
          this.dialogImageUrl = file.realurl;
          this.imgVisible = true;
          this.$refs.elImage.clickHandler()
        } else if (fileType == ".pdf") {
          window.open(file.realurl)
        } else {
          window.open(
            "https://view.officeapps.live.com/op/view.aspx?src=" + file.realurl//微软提供的开源接口，打开word，excel等文件
          );
        }

      },
      handleRemove(file, fileList) {
        this.fileList.forEach((item, i) => {
          if (item.uid == file.uid) {
            this.attachment.splice(i, 1);
          }
        })
        this.$emit('change', this.attachment)
      },
      // 图片上传失败时
      uploadError() {
        this.$message.error("图片上传失败!");
      },
      changeFile(option, fileList) {
        for (let i = 0;i < fileList.length;i++){
          if (option.name == fileList[i].name && option.uid != fileList[i].uid){
            this.msgWarning('该图片已存在,请选择其他图片')
            fileList.splice(fileList.indexOf(option),1)
            return ;
          }
        }
        let file = option.raw;
        // 文件格式判断
        let flag = this.handleBeforeUpload(file);
        if (!flag) {
          return false;
        }
        this.fileObj(option)
        // 文件base64
        this.saveImgBase64(option);
      },
      async saveImgBase64(option) {
        var loading = this.$loading({
          lock: true,
          text: '图片处理中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let file = option.raw;
        let _this = this;
        let {name: fileName, type: fileType} = file;
        let tmpObj = {
          fileBase64: "",
          fileName,
          fileType,
          fileUrl: ""
        };

        var type = file.name.substring(file.name.lastIndexOf("."));
        var fileCopy;
        if (type != '.pdf' && file.size > 1024 * 1024){
          await imageConversion.compress(file,0.3).then(res=>{
            fileCopy = res;
          })
        }else{
          fileCopy = file
        }
        let rd = new FileReader(); // 创建文件读取对象
        rd.readAsDataURL(fileCopy) // 文件读取装换为base64类型
        rd.onloadend = function (e) {
          loading.close();
          let arr1 = this.result.split(',');
          tmpObj.fileBase64Prefix = arr1[0];
          tmpObj.fileBase64 = arr1[1];
          _this.attachment.push(tmpObj);
          _this.$emit('change', _this.attachment)
        }

      },
      fileObj(option) {
        let file = option.raw;
        let fileType = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
        let url = '';
        option.realurl = option.url;
        if (fileType == ".pdf") {
          url = pdfImg;
        } else if (fileType == ".png" || fileType == ".webp" || fileType == ".jpg" || fileType == '.jpeg') {
          url = option.url;
        } else if (fileType == ".doc" || fileType == ".docx") {
          url = 'https://img1.baidu.com/it/u=1714136260,3766911961&fm=26&fmt=auto&gp=0.jpg';
        } else if (fileType == '.xls' || fileType == '.xlsx') {
          url = 'https://img1.baidu.com/it/u=1123362811,2189997153&fm=26&fmt=auto&gp=0.jpg';
        }
        option.url = url
      },
      fileListUrl(file) {
        let fileType = file.fileName.substring(file.fileName.lastIndexOf('.')).toLowerCase();
        let url = '';
        if (fileType == ".pdf") {
          url = pdfImg;
        } else if (fileType == ".png" || fileType == ".webp" || fileType == ".jpg" || fileType == '.jpeg') {
          url = file.fileUrlInner;
        } else if (fileType == ".doc" || fileType == ".docx") {
          url = 'https://img1.baidu.com/it/u=1714136260,3766911961&fm=26&fmt=auto&gp=0.jpg';
        } else if (fileType == '.xls' || fileType == '.xlsx') {
          url = 'https://img1.baidu.com/it/u=1123362811,2189997153&fm=26&fmt=auto&gp=0.jpg';
        }
        return url;
      },
      fileListObj(option) {
        let file = option.raw;
        let fileType = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
        let url = '';
        let realurl = option.url;
        if (fileType == ".pdf") {
          url = pdfImg;
        } else if (fileType == ".png" || fileType == ".webp" || fileType == ".jpg" || fileType == '.jpeg') {
          url = option.url;
        } else if (fileType == ".doc" || fileType == ".docx") {
          url = 'https://img1.baidu.com/it/u=1714136260,3766911961&fm=26&fmt=auto&gp=0.jpg';
        } else if (fileType == '.xls' || fileType == '.xlsx') {
          url = 'https://img1.baidu.com/it/u=1123362811,2189997153&fm=26&fmt=auto&gp=0.jpg';
        }
        let { name:fileName } = file;
        let listObj = {
          name: fileName,
          url,
          realurl
        };
        return listObj;
      },
      handleBeforeUpload(file) {
        let fileType = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
        let isType = true;
        if (!(fileType == 'jpg' || fileType == 'png')) {
          isType = false;
          this.msgWarning('请上传格式为.jpg, .png')
        }
        return isType;
      },
      // 覆盖默认的上传行为，可以自定义上传的实现，将上传的文件依次添加到fileList数组中,支持多个文件
      httpRequest(option) {

      },
    }
  }
</script>

<style scoped>

</style>
